import React from 'react';
import { Table, Form, Select, Button, Popconfirm, Input, Switch, Upload, message } from 'antd';
import { connect } from 'dva';

import ModalC from 'components/Modal/dns/optimal';

const Option = Select.Option;
const Search = Input.Search;

@connect(state => ({
  transpond: state.transpond,
  optimal: state.optimal,
}))
@Form.create()
class Pages extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      deviceId: null,
      visible: false,
      formatData: null,
      selectedRowKeys: [],
      type: 'add',
      currentId: null,
      searchValue: '',
      switchLoading: false,
    };
  }

  /**
   * 获取所有设备列表
   */
  getAllDevices = () => {
    this.props.dispatch({
      type: 'transpond/getAllDevices',
      payload: {},
      callback: data => {
        this.setState(
          {
            deviceId: data.id,
          },
          () => this.getTranspondList()
        );
      },
    });
  };

  /**
   * 获取所有域名组列表
   */
  getAllDomainGroup = () => {
    this.props.dispatch({
      type: 'transpond/getAllDomainGroup',
      payload: {},
    });
  };

  /**
   * 清除表单
   */
  clearForm = () => {
    this.props.form.resetFields();
  };

  /**
   * 筛选
   */
  select = value => {
    this.clearForm();
    this.setState(
      {
        deviceId: value,
      },
      () => {
        this.getTranspondList();
      }
    );
  };

  //根据服务Id获取转发列表
  getTranspondList = (pageNum = 1, pageSize = 10) => {
    const { dispatch } = this.props;
    const { deviceId, searchValue } = this.state;
    dispatch({
      type: 'optimal/getList',
      payload: {
        pageNum,
        pageSize,
        deviceId,
        domain: searchValue,
      },
    });
  };

  /**
   * 提交按钮
   */

  //提交数据
  submit = values => {
    const { type, currentId, deviceId } = this.state;
    if (type === 'add') {
      this.props.dispatch({
        type: 'optimal/add',
        payload: {
          ...values,
          deviceId,
        },
        callback: (pageNum, pageSize) => {
          this.getTranspondList(pageNum, pageSize);
          this.closeModal();
        },
      });
    } else {
      this.props.dispatch({
        type: 'optimal/update',
        payload: {
          ...values,
          id: currentId,
          deviceId,
        },
        callback: (pageNum, pageSize) => {
          this.getTranspondList(pageNum, pageSize);
          this.closeModal();
        },
      });
    }
  };

  /**
   * 开启关闭域名
   */
  handleSwitch = value => {
    this.setState({
      currentId: value.id,
      switchLoading: true,
    });
    this.props.dispatch({
      type: 'optimal/update',
      payload: {
        id: value.id,
        deviceId: value.deviceId,
        openState: value.openState === 0 ? 1 : 0,
      },
      callback: (pageNum, pageSize) => {
        this.getTranspondList(pageNum, pageSize);
        this.setState({
          currentId: null,
          switchLoading: false,
        });
      },
    });
  };

  /**
   * 删除
   */
  delete = ids => {
    this.props.dispatch({
      type: 'optimal/deleteOptimal',
      payload: {
        ids,
      },
      callback: (pageNum, pageSize) => {
        this.setState({
          selectedRowKeys: [],
        });
        this.getTranspondList(pageNum, pageSize);
      },
    });
  };
  deleteAll = () => {
    const { selectedRowKeys } = this.state;
    this.delete(selectedRowKeys);
  };
  //批量删除
  onSelectChange = selectedRowKeys => {
    this.setState({ selectedRowKeys });
  };

  /**
   * modal
   */
  closeModal = () => {
    this.setState({
      visible: false,
      formatData: null,
    });
  };
  //新增编辑
  updateBtn = (type = 'add', record = null) => {
    if (type === 'add') {
      this.setState({
        type: 'add',
        visible: true,
      });
    } else {
      this.setState({
        type: 'edit',
        currentId: record.id,
        visible: true,
        formatData: record,
      });
    }
  };

  /**
   * 翻页
   */
  pageChange = page => {
    this.getTranspondList(page);
  };

  //搜索
  search = value => {
    this.setState(
      {
        searchValue: value,
      },
      () => this.getTranspondList()
    );
  };

  /**
   * 刷新配置
   */
  freshConfig = () => {
    const { deviceId } = this.state;
    this.props.dispatch({
      type: 'transpond/freshConfig',
      payload: {
        deviceId,
      },
    });
  };

  /**
   * 导入
   */
  upload = data => {
    if (data.file.status === 'done') {
      if (data.file.response.code === 200) {
        message.info('导入成功');
        this.getTranspondList();
      } else {
        message.error(data.file.response.msg);
      }
    }
  };

  componentDidMount() {
    this.getAllDevices();
    this.getAllDomainGroup();
  }

  render() {
    const {
      transpond: { allDevices, allDomainGroup },
      optimal: { list, total, pageNum, pageSize, loading },
    } = this.props;
    const { deviceId, selectedRowKeys, formatData, visible, switchLoading, currentId } = this.state;

    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };

    const pagination = {
      onChange: this.pageChange,
      total,
      pageSize,
      current: pageNum,
    };

    const columnsDns = [
      {
        title: '域名',
        width: 100,
        dataIndex: 'domain',
      },
      { title: '服务列表', dataIndex: 'serverList', width: 100 },
      { title: '健康检查地址', dataIndex: 'checkAddress', width: 100 },
      { title: '健康检查间隔', dataIndex: 'checkInterval', width: 100 },
      { title: '备注', dataIndex: 'remark', width: 100 },
      {
        title: '状态',
        dataIndex: 'openState',
        width: 100,
        render: (text, record) => (
          <Switch
            loading={switchLoading && currentId === record.id}
            onChange={() => this.handleSwitch(record)}
            checked={text === 1}
            checkedChildren="开"
            unCheckedChildren="关"
          />
        ),
      },
      {
        title: '操作',
        render: (text, record) => (
          <>
            <span onClick={() => this.updateBtn('edit', record)} className="btnG">
              详情
            </span>
          </>
        ),
        width: 150,
      },
    ];

    return (
      <>
        <h3 className="head">优化管理</h3>
        <div style={{ padding: '10px 20px' }}>
          <div>
            <span>设备:</span>
            <Select
              value={deviceId}
              onChange={this.select}
              style={{ width: '150px', marginLeft: '10px' }}
            >
              {allDevices.map(item => (
                <Option value={item.id} key={item.id}>
                  {item.deviceName}
                </Option>
              ))}
            </Select>
            <Search
              enterButton
              placeholder="输入域名搜索"
              style={{ width: '250px', marginLeft: '20px' }}
              onSearch={this.search}
            />
          </div>

          <div>
            <div className="mt20">
              <Button type="primary" icon="plus" onClick={() => this.updateBtn()}>
                新增
              </Button>
              {selectedRowKeys.length > 0 && (
                <Popconfirm
                  title="确定要删除吗？"
                  okText="确定"
                  cancelText="取消"
                  onConfirm={() => this.deleteAll()}
                >
                  <Button
                    className="ml10"
                    type="primary"
                    disabled={selectedRowKeys <= 0}
                    icon="delete"
                  >
                    批量删除
                  </Button>
                </Popconfirm>
              )}

              <Popconfirm
                title="确定要启用配置吗？"
                okText="确定"
                cancelText="取消"
                onConfirm={() => this.freshConfig()}
              >
                <Button className="ml10" type="primary" icon="tool">
                  启用配置
                </Button>
              </Popconfirm>
              <Upload
                headers={{
                  accessToken: localStorage.getItem('tokenId'),
                }}
                action="/api/api/v1/optimize/importExcel"
                onChange={this.upload}
                showUploadList={false}
              >
                <Button className="ml10" type="primary" icon="import">
                  导入
                </Button>
              </Upload>
              <Table
                rowKey="id"
                loading={loading}
                dataSource={list}
                columns={columnsDns}
                rowSelection={rowSelection}
                pagination={pagination}
              />
            </div>
          </div>

          <ModalC
            list={allDomainGroup}
            visible={visible}
            close={this.closeModal}
            formatData={formatData}
            submit={this.submit}
          />
        </div>
      </>
    );
  }
}

export default Pages;
